package com.zglc.ms.shop.util;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.zglc.ms.base.constants.ResponseCodeHelper;

public class CommonUtils {
	
	public static final String RETURN_CODE = "code";
	
	public static final String RETURN_MSG = "msg";
	
	public static final String RETURN_DATA = "data";
	
	private static Map<String, Object> userNotExistMap = new HashMap<>();
	
	public static final int MAX_CACHE_TIME_30_MINUTE = 30 * 60 * 1000;
	
	public static final String SPLIT = "zg";
	
	public static Map<String,String> clientMap = new HashMap<>();
	
	static {
		userNotExistMap.put("code", ResponseCodeHelper.COMMON_USER_NOT_EXIST);
		userNotExistMap.put("msg", "用户未注册");
		userNotExistMap = Collections.unmodifiableMap(userNotExistMap);
		clientMap.put("module", "shop");
		clientMap = Collections.unmodifiableMap(clientMap);
	}
	
	public static Map<String, Object> userNotExistResponse(){
		return userNotExistMap;
	}
	
	public static Map<String, Object> successResponse(){
		Map<String, Object> map = new HashMap<>();
		map.put(RETURN_CODE, ResponseCodeHelper.SUCCESS);
		map.put(RETURN_MSG, "success");
		return map;
	}
	
	/**
	 * 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址;
	 * 
	 * @param request
	 * @return
	 * @throws IOException
	 */
	public static String getIpAddress(HttpServletRequest request) {
		// 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址

		String ip = request.getHeader("X-Forwarded-For");

		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("WL-Proxy-Client-IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_CLIENT_IP");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getHeader("HTTP_X_FORWARDED_FOR");
			}
			if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
				ip = request.getRemoteAddr();
			}
		} else if (ip.length() > 15) {
			String[] ips = ip.split(",");
			for (int index = 0; index < ips.length; index++) {
				String strIp = (String) ips[index];
				if (!("unknown".equalsIgnoreCase(strIp))) {
					ip = strIp;
					break;
				}
			}
		}
		return ip;
	}

}
